﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace DNA.Mvc
{
    /// <summary>
    /// Present the Web site object.
    /// </summary>
    [Table("dna_WebSettings")]
    public class Web
    {
        public Web()
        {
            Created = DateTime.UtcNow;
            MostOnlined = DateTime.UtcNow;
            Type = 0;
            CacheDuration = 0;
            IsEnabled = true;
        }

        /// <summary>
        /// Gets/Sets the web site id.
        /// </summary>
        [Key]
        [Column("Id", Order = 1)]
        public virtual int Id { get; set; }

        /// <summary>
        /// Gets/Sets the web site unique name. Top site is "home"
        /// </summary>
        [Column("Name"), MaxLength(1024), Required]
        public virtual string Name { get; set; }

        /// <summary>
        /// Get/Sets the display title text of the website.
        /// </summary>
        [MaxLength(50)]
        public virtual string Title { get; set; }

        [Required]
        public virtual int Type { get; set; }

        /// <summary>
        /// Gets/Sets the current theme name.
        /// </summary>
        [MaxLength(255)]
        public virtual string Theme { get; set; }

        /// <summary>
        /// Gets/Sets the timezone name of the website.
        /// </summary>
        [MaxLength(255)]
        public virtual string TimeZone { get; set; }

        [Column(TypeName = "ntext")]
        public virtual string AllowExtensions { get; set; }

        [Required]
        public virtual int CacheDuration { get; set; }

        [Column(TypeName = "ntext")]
        public virtual string Copyright { get; set; }

        [Required]
        public virtual DateTime Created { get; set; }

        [Column(TypeName = "ntext")]
        public virtual string CssText { get; set; }

        [Column(TypeName = "ntext")]
        public virtual string Data { get; set; }

        [MaxLength(50)]
        public virtual string DefaultLanguage { get; set; }

        [MaxLength(1024)]
        public virtual string DefaultUrl { get; set; }

        [Column(TypeName = "ntext")]
        public virtual string Description { get; set; }

        public virtual bool EnableUserRegistration { get; set; }

        [Required]
        public virtual bool IsEnabled { get; set; }

        [MaxLength(1024)]
        public virtual string Layout { get; set; }

        [MaxLength(1024)]
        public virtual string LogoImageUrl { get; set; }

        [MaxLength(1024)]
        public virtual string MasterName { get; set; }

        public virtual int MaximumFileSize { get; set; }

        public virtual DateTime MostOnlined { get; set; }

        public virtual int MostOnlineUserCount { get; set; }

        [Required, MaxLength(256)]
        public virtual string Owner { get; set; }

        [Column(TypeName = "ntext")]
        public virtual string SearchKeywords { get; set; }

        [MaxLength(1024)]
        public virtual string ShortcutIconUrl { get; set; }

        public virtual ICollection<WebPage> WebPages { get; set; }

        #region Extension properties
        private WebMasterTools masterTools;
        private IDictionary<string, object> properties;

        [NotMapped]
        public WebMasterTools MasterTools
        {
            get
            {
                if (masterTools == null)
                    masterTools = new WebMasterTools(this);
                return masterTools;
            }
        }

        /// <summary>
        /// Gets the additional setting values for the website.
        /// </summary>
        [NotMapped]
        public IDictionary<string, object> Properties
        {
            get
            {
                if (properties == null)
                {
                    if (!string.IsNullOrEmpty(Data))
                    {
                        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        properties = (IDictionary<string, object>)serializer.DeserializeObject(Data);
                    }
                    else
                        properties = new Dictionary<string, object>();
                }
                return properties;
            }
        }

        private void SetValue(string key, object value)
        {
            if (Properties.ContainsKey(key))
                Properties[key] = value;
            else
                Properties.Add(key, value);
        }

        private string GetValue(string key)
        {
            if (Properties.ContainsKey(key))
                return Properties[key] as string;
            else
                return "";
        }

        private T GetValue<T>(string key)
        {
            if (Properties.ContainsKey(key))
                return (T)Properties[key];
            return default(T);
        }

        [NotMapped]
        public LogoLayouts LogoLayout
        {
            get
            {
                return GetValue<LogoLayouts>("LogoLayout");
            }
            set
            {
                SetValue("LogoLayout", value);
            }
        }

        [NotMapped]
        public TimeZoneInfo TimeZoneInfo
        {
            get
            {
                if (string.IsNullOrEmpty(this.TimeZone))
                    return TimeZoneInfo.Local;
                else
                    return TimeZoneInfo.FindSystemTimeZoneById(this.TimeZone);
            }
        }

        /// <summary>
        /// Sets the extensions allow to upload to the website
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        public bool IsAllowUpload(string extension)
        {
            if (string.IsNullOrEmpty(this.AllowExtensions))
                return false;

            string[] exts = AllowExtensions.ToLower().Split(new char[] { '|' });
            return exts.Contains(extension.ToLower());
        }

        public bool IsTrusted(Uri appUrl, Uri url)
        {

            if (appUrl.Authority.Equals(url.Authority, StringComparison.OrdinalIgnoreCase))
                return true;

            if (MasterTools.PreventUntrustLinks)
            {
                if (!string.IsNullOrEmpty(MasterTools.TrustDomains))
                    return MasterTools.GetTrustDomains().Contains(url.Authority.ToLower());
                return false;
            }
            return true;
        }

        [NotMapped]
        public bool IsRoot
        {
            get
            {
                if (string.IsNullOrEmpty(Name))
                    return false;

                return Name.Equals("home", StringComparison.OrdinalIgnoreCase);
            }
        }

        /// <summary>
        /// Gets the web root folder path
        /// </summary>
        [NotMapped]
        public string WebFolder
        {
            get
            {
                return "/webshared/" + Name + "/";
            }
        }
        #endregion
    }
}
